﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 产品是否锁定服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class productislockService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<productislock> _productislockRep;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictTypeService _sysDictTypeService;

    public productislockService(SqlSugarRepository<productislock> productislockRep, ISqlSugarClient sqlSugarClient, SysDictTypeService sysDictTypeService)
    {
        _productislockRep = productislockRep;
        _sqlSugarClient = sqlSugarClient;
        _sysDictTypeService = sysDictTypeService;
    }

    /// <summary>
    /// 分页查询产品是否锁定 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询产品是否锁定")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<productislockOutput>> Page(PageproductislockInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _productislockRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.type.Contains(input.Keyword) || u.encoding.Contains(input.Keyword) || u.lockcause.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.type), u => u.type.Contains(input.type.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.encoding), u => u.encoding.Contains(input.encoding.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.lockcause), u => u.lockcause.Contains(input.lockcause.Trim()))
            .WhereIF(input.process != null, u => u.process == input.process)
            .WhereIF(input.lockstarttimeRange?.Length == 2, u => u.lockstarttime >= input.lockstarttimeRange[0] && u.lockstarttime <= input.lockstarttimeRange[1])
            .WhereIF(input.lockendtimeRange?.Length == 2, u => u.lockendtime >= input.lockendtimeRange[0] && u.lockendtime <= input.lockendtimeRange[1])
            .LeftJoin<Processmanage>((u, process) => u.process == process.Id)
            .Select((u, process) => new productislockOutput
            {
                Id = u.Id,
                type = u.type,
                encoding = u.encoding,
                process = u.process,
                processFkDisplayName = $"{process.processname}",
                lockstarttime = u.lockstarttime,
                lockendtime = u.lockendtime,
                lockcause = u.lockcause,
                states = u.states,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取产品是否锁定详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取产品是否锁定详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<productislock> Detail([FromQuery] QueryByIdproductislockInput input)
    {
        return await _productislockRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加产品是否锁定 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加产品是否锁定")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddproductislockInput input)
    {
        var entity = input.Adapt<productislock>();
        return await _productislockRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新产品是否锁定 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新产品是否锁定")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateproductislockInput input)
    {
        var entity = input.Adapt<productislock>();
        await _productislockRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除产品是否锁定 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除产品是否锁定")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteproductislockInput input)
    {
        var entity = await _productislockRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _productislockRep.FakeDeleteAsync(entity);   //假删除
        //await _productislockRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除产品是否锁定 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除产品是否锁定")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteproductislockInput> input)
    {
        var exp = Expressionable.Create<productislock>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _productislockRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _productislockRep.FakeDeleteAsync(list);   //假删除
        //return await _productislockRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataproductislockInput input)
    {
        var processData = await _productislockRep.Context.Queryable<Processmanage>()
            .InnerJoinIF<productislock>(input.FromPage, (u, r) => u.Id == r.process)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.processname}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "process", processData },
        };
    }
    
    /// <summary>
    /// 导出产品是否锁定记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出产品是否锁定记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageproductislockInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportproductislockOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        var typeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "product_lock_type" }).Result.ToDictionary(x => x.Value, x => x.Label);
        list.ForEach(e => {
            e.typeDictLabel = typeDictMap.GetValueOrDefault(e.type ?? "", e.type);
        });
        return ExcelHelper.ExportTemplate(list, "产品是否锁定导出记录");
    }
    
    /// <summary>
    /// 下载产品是否锁定数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载产品是否锁定数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportproductislockOutput>(), "产品是否锁定导入模板", (_, info) =>
        {
            if (nameof(ExportproductislockOutput.processFkDisplayName) == info.Name) return _productislockRep.Context.Queryable<Processmanage>().Select(u => $"{u.processname}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入产品是否锁定记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入产品是否锁定记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var typeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "product_lock_type" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var stream = ExcelHelper.ImportData<ImportproductislockInput, productislock>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 工序
                    var processLabelList = pageItems.Where(x => x.processFkDisplayName != null).Select(x => x.processFkDisplayName).Distinct().ToList();
                    if (processLabelList.Any()) {
                        var processLinkMap = _productislockRep.Context.Queryable<Processmanage>().Where(u => processLabelList.Contains($"{u.processname}")).ToList().ToDictionary(u => $"{u.processname}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.process = processLinkMap.GetValueOrDefault(e.processFkDisplayName ?? "");
                            if (e.process == null) e.Error = "工序链接失败";
                        });
                    }
                    
                    // 映射字典值
                    foreach(var item in pageItems) {
                        if (string.IsNullOrWhiteSpace(item.typeDictLabel)) continue;
                        item.type = typeDictMap.GetValueOrDefault(item.typeDictLabel);
                        if (item.type == null) item.Error = "类型字典映射失败";
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<productislock>>();
                    
                    var storageable = _productislockRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.type?.Length > 64, "类型长度不能超过64个字符")
                        .SplitError(it => it.Item.encoding?.Length > 64, "编码长度不能超过64个字符")
                        .SplitError(it => it.Item.lockcause?.Length > 64, "锁定原因长度不能超过64个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
